package com.flute.icrawler.app.result;

import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.entity.CrawlResult;
import com.flute.icrawler.app.service.CrawlService;

/**
 * 普通文件存储方式
 * 
 * @author jiangbo
 * 
 */
public class FileStoreImp implements IStoreable {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(FileStoreImp.class);

	public FileStoreImp() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 返回文件存储的路径 如果为空则存储失败
	 */
	@Override
	public String store(CrawlResult crawlResult) {
		// TODO Auto-generated method stub

		String outPutPath = crawlResult.getFileSavePath();
		FileOutputStream out = null;

		try {

			out = new FileOutputStream(outPutPath);

			byte[] content = crawlResult.getContent();
			if (null == content) {
				LOGGER.warn("content is null url=" + crawlResult.getUrl());
				return null;
			}

			out.write(content);

			out.flush();

		} catch (IOException e) {
			LOGGER.error("{}", e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				out = null;

			} catch (Exception ex) {
				LOGGER.error("{}", ex);
			}
		}

		if (null == outPutPath) {
			LOGGER.warn("save failed url=" + crawlResult.getUrl());
			return "";
		}

		CrawlService.getInstance().logResult(crawlResult.getHostName(),
				(crawlResult.getUrl() + "->" + outPutPath));

	//	LOGGER.info("save ok:" + crawlResult.getUrl() + "->" + outPutPath);
		return outPutPath;

	}

	@Override
	public void close() {
		// TODO Auto-generated method stub

	}

}
